package com.mhh.selary.backend.config;

import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.mhh.sdk.utils.structure.DataUtils;
import com.mhh.selary.backend.dao.entity.config.SelaryConfigPropEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.regex.Matcher;

/**
 * @author mhh
 * @date 2020-11-06 16:25:51
 */
@Slf4j
public class EnvPropConfig {

    private EnvPropConfig() {

    }

    private static Table<Long, String, String> propTable = HashBasedTable.create();

    private static final String KEY_TEMPLATE = "${%s}";

    public static void init(List<SelaryConfigPropEntity> propList) {
        propList.stream()
                .filter(prop -> StringUtils.isNotBlank(prop.getPropKey()) && StringUtils.isNotBlank(prop.getPropValue()))
                .forEach(prop -> propTable.put(prop.getEnvId(), String.format(KEY_TEMPLATE, prop.getPropKey()), prop.getPropValue()));
    }

    public static void put(Long envId, String propKey, String propValue) {
        if (StringUtils.isBlank(propKey) || StringUtils.isBlank(propValue)) {
            return;
        }
        propTable.put(envId, String.format(KEY_TEMPLATE, propKey), propValue);
    }

    public static String get(Long envId, String propKey) {
        return propTable.get(envId, propKey);
    }

    public static void del(Long envId, String propKey) {
        if (StringUtils.isBlank(propKey)) {
            return;
        }
        propTable.remove(envId, String.format(KEY_TEMPLATE, propKey));
    }

    public static String replaceHolder(Long envId, String source) {
        if (envId == null) {
            return source;
        }
        Matcher matcher = DataUtils.placeHolderMatch(source);
        while (matcher.find()) {
            String placeholder = matcher.group();
            String realValue = get(envId, placeholder);
            if (realValue == null) {
                realValue = "";
            }
            source = source.replace(placeholder, realValue);
        }
        return source;
    }
}
